MyDesktop.InStorageRecordWindow = Ext.extend(Ext.app.Module, {
    id:'inRecord-win',
    init : function(){
        this.launcher = {
            text: '入库记录',
            iconCls:'icon-grid',
            handler : this.createWindow,
            scope: this
        }
    },
  
	record : Ext.data.Record.create([
        	{name : 'docID',mapping : 'docID',type : 'string'},      
        	{name : 'partnerId',mapping : 'partnerId',type : 'string'},
        	{name : 'partnerName',mapping : 'partnerName',type : 'string'},
        	{name : 'totalAmount',mapping : 'totalAmount',type : 'string'},
        	{name : 'remarks',mapping : 'remarks',type : 'string'},
        	{name : 'buyDate',mapping : 'buyDate',type : 'date',dateFormat:'Y-m-d'},
        	{name : 'handler',mapping : 'handler',type : 'string'},
        	{name : 'createMan',mapping : 'createMan',type : 'string'},
        	{name : 'createTime',mapping : 'createTime',type : 'date',dateFormat:'Y-m-d'},
        	{name : 'auditor',mapping : 'auditor',type : 'string'},
        	{name : 'auditTime',mapping : 'auditTime',type : 'date',dateFormat:'Y-m-d'},
        	{name : 'stateName',mapping : 'stateName',type : 'string'},
        	{name : 'state',mapping : 'state',type : 'string'}
	]),
	
	browserBuyItem:function(id){},
	
	auditBuyItem:function(id){},
	
    createWindow : function(){
        var desktop = this.app.getDesktop();
        var win = desktop.getWindow('inRecord-win');
		
        var module = this;
        
        if(!win){
		
          function addProduct(){
            	if(product_detailForm.form.el){
            		product_detailForm.form.el.dom.reset();            	
            	}else{
            		product_detailForm.form.reset();
            	}
                addOrEditProduct_win.buttons[0].setText('新增');
		        addOrEditProduct_win.isAdd = true;
		        addOrEditProduct_win.setTitle("商品入库");
		        addOrEditProduct_win.show();
          }	
        	
           function submitForm(){
			    var form=buyItem_form.getForm();
				var totalRecords =grid_buyItem_store.getRange();
				var buyItem = [];
				for(var i=0;i<totalRecords.length;i++){
				   
				    buyItem.push(totalRecords[i].data);
				
				}
            	if(!form.isValid()){
	         		 return;
	      		}
				
					Ext.Ajax.request({
	           			url:app.url+'/admin/storage/createBuy.do',
	           			method :"post",
						jsonData :Ext.encode({buy:form.getValues(),buyItems:buyItem}),
						waitMsg : '正在提交数据,请稍候...',
	          			success:function(response,options){							
							Ext.MessageBox.alert("提示","操作成功!");
							clearBuyItemForm();
							grid_debit.getBottomToolbar().doRefresh();//刷新列表 
	           			},
	           			failure:function(response,options){
	                		Ext.MessageBox.alert("提示","发生异常，请稍候处理!");    
	           			}
	       			});
				
		}		
		var store=new Ext.data.Store({
        	url : app.url+'/admin/strorage/inRecord.do',
			baseParams:{start:0,limit:20},
        	reader : new Ext.data.JsonReader({totalProperty : 'totalProperty',root : 'root'}, 
        	this.record)
        });
		
		var stockFind=function() {
            if(find_form.getForm().isValid())
            {
                find_form.form.submit({
                    waitMsg : '正在查寻......',
                    url : app.url+'/admin/strorage/inRecord.do',
					params :{limit:20},
					method:'POST',
                    timeout: 3000,
                    success : function(form, action) {
                     store.loadData(action.result);
                    },
                    failure : function(form, action) {
                        store.loadData(action.result);
                    }
                });
            }
        };	
        
     var itemRecord= Ext.data.Record.create([
	        {name : 'goodsId'}, 
        	{name : 'name'}, 
        	{name : 'productCode'},
        	{name : 'unit'},
        	{name : 'amount'},
        	{name : 'totalAmount'},
			{name : 'storageId'},
			{name : 'storageName'}
    ]);
    	
	var grid_buyItem_cm = new Ext.grid.ColumnModel([
	       new Ext.grid.RowNumberer(),
		   {header : '',width : 30,dataIndex : 'goodsId',hidden:true}, 
		   {header : '商品名称',width : 130,dataIndex : 'name'}, 
		   {header : '商品编码',width : 130,dataIndex : 'productCode'},
		   {header : '单位',width : 50,dataIndex : 'unit'},
		   {header : '数量', width: 80, dataIndex : 'amount'},
		   {header : "单价", width:100, dataIndex : 'unitPrice', renderer: Ext.util.Format.cnMoney},
		   {header : '金额',width:100,dataIndex : 'totalAmount', groupable: false,
		         renderer:function (v, params, record){
		         	return Ext.util.Format.cnMoney(record.data.amount * record.data.unitPrice);
		         },
		         summaryRenderer: Ext.util.Format.cnMoney
		   },		   
		   {header : '仓库',width : 100,dataIndex : 'storageName'}
	]);
	
    var grid_buyItem_store = new Ext.data.JsonStore({
	      root:'',
		  fields:[
    	    {name : 'name',mapping : 'name',type : 'string'}, 
    		{name : 'productCode',mapping : 'productCode',type : 'string'},
    	    {name : 'unit',mapping : 'unit',type : 'string'}, 
    	    {name : 'amount',mapping : 'amount'}, 
    		{name : 'unitPrice',mapping : 'unitPrice'},
    		{name : 'storageId',mapping : 'storageId',type : 'int'},
			{name : 'storageName',mapping : 'storageName',type : 'string'}
		  ]
	}); 

    var  grid_buyItem = new Ext.grid.EditorGridPanel({
        	title : '入库条目',
        	iconCls : 'icon-grid',
        	collapsible: false,
			border:false,
            region: 'center',
            margins: '5 0 0 0',
			columnLines :true,
			autoScroll : true,
			clicksToEdit: 1,
			enableHdMenu : false,
        	viewConfig:
        	{
        	 forceFit:false,
        	 scrollOffset:15
        	 },
			 tbar:[{
                    text:'增加',
                    tooltip:'',
                    iconCls:'add',
					handler : addProduct
                   },'-',{
                    text:'删除',
                    tooltip:'',
                    iconCls:'remove',
					handler : function(){
			  				var record = grid_buyItem.getSelectionModel().getSelected();
		       				if (record) {
			     				grid_buyItem_store.remove(record);
								grid_buyItem.getView().refresh();
			   				}
			 			}
                   }],
        	autoWidth : true,
        	region : 'center',
        	cm : grid_buyItem_cm,
        	ds : grid_buyItem_store,
        	sm : new Ext.grid.CheckboxSelectionModel({singleSelect : false}),
        	enableColumnMove : false,
        	trackMouseOver : false,
        	frame : true,
			clicksToEdit: 1
        });
        
        var goodsCombo = getGoodsCombo(false);
        
        goodsCombo.on('select',function(){
        	var goodsId = this.getValue();
        	Ext.Ajax.request({
        		url:app.url+'/admin/com/getGoods.do?id='+goodsId,
	            method :"post",
			    //jsonData :{id:goodsId},
			    //waitMsg : '正在提交数据,请稍候...',
	            success:function(response,options){
	            	var resp = Ext.decode(response.responseText);
					product_detailForm.getForm().findField('productCode').setValue(resp.typeCode);
					product_detailForm.getForm().findField('unit').setValue(resp.unit)	
	           	},
	           	failure:function(response,options){
	               	Ext.MessageBox.alert("提示","发生异常，请稍候处理!");    
	           	}
        	});
        });
        
         var product_detailForm =new Ext.FormPanel({
                		border : true,
                		labelAlign : 'right',
                		labelWidth : 60,
						frame : true,
						height: 190,
						//manager:this.app.getDesktop().windows,
                		items : [{
									layout:'column',
									items:[{
        								columnWidth : .33,
        								layout : 'form',
        								items : [goodsCombo]
								    },{
        								columnWidth : .33,
        								layout : 'form',
        								items : [{xtype : 'textfield',fieldLabel : '商品编码',name : 'productCode',anchor : '100%',disabled : true}]
								    },{
        								columnWidth : .33,
        								layout : 'form',
        								items : [{xtype : 'textfield',fieldLabel : '单位',name : 'unit',anchor : '100%',disabled : true}]
								    }]
							},{// 2 row
									layout:'column',
									items:[{
        								columnWidth : .33,
        								layout : 'form',
        								items : [{xtype : 'numberfield',fieldLabel : '数量',name : 'amount',anchor : '100%',allowBlank : false, minLength : 1,maxLength : 9,itemId:'addform'}]
								    },{
        								columnWidth : .33,
        								layout : 'form',
        								items : [{xtype : 'numberfield',fieldLabel : '进价',name : 'unitPrice',anchor : '100%',allowBlank : false, minLength : 1,maxLength : 9}]
								    },{
        								columnWidth : .33,
        								layout : 'form',
        								items : [getStorageCombo(false)]
								    }]
							}]
						});

       		 
       		 var addOrEditProduct_win = new Ext.Window({
       		 	layout:'fit',
		    	width:630,
		    	closeAction:'hide',
		   		height:200,
				resizable :false,
				shadow : true,
				modal :true,
		   	    closable:true,
		    	bodyStyle:'padding:5 5 5 5',		    	
		    	animCollapse:true,
				items:[product_detailForm],
				buttonAlign : 'center',
				buttons:[{
                			     	//id:'commitButton',
									iconCls : 'save',
									handler:function(){	
									  var form=product_detailForm.getForm();
									  if(!form.isValid()){
	         		                     return;
	      		                       }
									   var values = form.getValues();
	      		                       values.name = form.findField('goodsId').getRawValue();
	      		                       values.storageName = form.findField('storageId').getRawValue();
									   var r=new itemRecord(values);
									   //alert(Ext.encode(values));
                			     	   grid_buyItem_store.add(r);
									   form.reset();
                			     	}
                			       },{
                			     	 //id:'closeButton',
									 text : '关闭',
						             iconCls : 'close',
                			     	 handler:function(){				     		
                			     	    addOrEditProduct_win.hide();
                			     	}
                			      }]
       		 });
    	 
        
    var buyItem_form = new Ext.FormPanel({
            	border : true,
				region: 'north',
                labelAlign : 'right',
                labelWidth : 60,
				frame : true,
				height: 100,
				manager:this.app.getDesktop().windows,
            	items : [{                   	
                    layout:'hbox',
                    layoutConfig:{align:'middle'},
                    items:[
                       {
		                xtype:'spacer',
                        flex:1
		               },{
                        xtype:'label',
                        text:'入库单',
                         style: {font:'bold 20px arial,serif'}
                       },{
		                xtype:'spacer',
                        flex:1
		               },{
                      	 xtype:'label',
                      	 text : '单据号:',                     	      
                      	 style:{fontSize:'13px'}
                       },{
						 xtype : 'textfield',																				  
					     name : 'docID',							 
						 readOnly :true,
						 style:{background:'#dddddd', width:'120px'}
					   }
                    ]
                  },{
                    html:'<hr color="#34A4E0" />'
                  },{
									layout:'column',
									items:[{
        								columnWidth : .3,
        								layout : 'form',
        								items : [getPartnerCombo()]
								    },{
        								columnWidth : .2,
        								layout : 'form',
        								items : [getEmployeeCombo('经手人')]
								    },{
        								columnWidth : .25,
        								layout : 'form',
        								items : [{xtype : 'datefield',fieldLabel : '购买日期',name : 'buyDate',anchor : '100%',allowBlank : false,format:'Y-m-d'}]
								    }]
							},{// 4 row
									layout:'column',
									items:[{
        								columnWidth : .75,
        								layout : 'form',
        								items : [{xtype : 'textarea',fieldLabel : '备注',name : 'remarks',anchor : '100%',height: 48}]
								    }]
							}]
    });
    
    var addItem_win = new Ext.Window({
    	title:'入库',
        width:app.maxWidth,
        height:app.maxHeight,
        iconCls: 'icon-grid',
        shim:false,
        animCollapse:false,
        constrainHeader:true,
        layout: 'border',
        items:[grid_buyItem,buyItem_form],        
        buttonAlign : 'center',
        buttons: [{
             text:'保存',
		     iconCls : 'save',
			 handler:submitForm
           },{
             text: '取消',
			 iconCls : 'close',
             handler: function(){
                   addItem_win.hide();
             }
           }]    
    });    
    
	var tb =new Ext.Toolbar({
        height: 35,
		region: 'north',
        items: [{
        	 xtype: 'button',
             text: '新增',
			 iconCls: 'add',
			 scale: 'small',
			 handler: function(){
			 	  clearBuyItemForm();
				  addItem_win.show();
				}
           
            },'-',{
        	 xtype: 'button',
             text: '审核'
           
          }]
     });
		function clearBuyItemForm(){
			/*if(buyItem_form.form.el){
               buyItem_form.form.el.dom.reset();            	
            }else{*/
               buyItem_form.form.reset();
            //}
            grid_buyItem_store.removeAll();
		}
        var find_form = new Ext.FormPanel({
            	border : true,
				region: 'north',
				collapsible: true,
                labelAlign : 'right',
                labelWidth : 60,
				frame : true,
				height: 100,
            	items : [{
									layout:'column',
									items:[{
        								columnWidth : .3,
        								layout : 'form',
        								items : [getStorageCombo(true)]
								    },{
        								columnWidth : .2,
        								layout : 'form',
        								items : [getEmployeeCombo('经手人',true)]
								    },{
        								columnWidth : .25,
        								layout : 'form',
        								items : [{xtype : 'textfield',fieldLabel : '入库单号',name : 'docID',anchor : '100%'}]
								    },{
        								columnWidth : .25,
        								layout : 'form',
        								items : [getGoodsCombo(true)]
								    }]
							},{
							   layout:'column',
							   items:[{
        							columnWidth : .25,
        							layout : 'form',
        							items : [{xtype : 'datefield',fieldLabel : '开始日期',name : 'buyDate',anchor : '100%',format:'Y-m-d'}]
							   },{
        							columnWidth : .25,
        							layout : 'form',
        							items : [{xtype : 'datefield',fieldLabel : '结束日期',name : 'buyDate',anchor : '100%',format:'Y-m-d'}]
							   },{  
							        columnWidth : .25,
        							layout : 'form',
        							items : [{
									      xtype : 'button',
										  text : '查询',
										  handler : stockFind
										  }]
							   },{
							        columnWidth : .25,
        							layout : 'form',
        							items : [{xtype : 'button',text : '清空'}]
							   }]
							}]
						});
						
	function loadBuyItemForm(id){
		buyItem_form.load({
		      url:app.url+'/admin/storage/buyInfo.do?id='+id,
		      waitMsg : '正在提载入数据...',
			  success:function(form, action){			  	  
			      grid_buyItem_store.loadData(action.result.data.items);					
	          },
	          failure:function(form, action){
	              Ext.MessageBox.alert("提示","发生异常，请稍候处理!");    
	          }
		 });
	}
						
	 browserBuyItem = function(id){		
		 loadBuyItemForm(id);
		 addItem_win.buttons[0].disable();
		 if(addItem_win.buttons[2]){
		 	//addItem_win.buttons[2].hide();
		    //addItem_win.remove(addItem_win.buttons[2]);
		 	addItem_win.buttons[2].disable();
		 }
		 addItem_win.show();
	 }
	
     auditBuyItem = function(id){
		loadBuyItemForm(id);
		addItem_win.buttons[0].enable();
		addItem_win.buttons[0].setText('审核通过');
		addItem_win.addButton({
		    text: '审核不通过',
		    iconCls : 'close'},
		    function(){
		       alert("审核不通过");
		});
		addItem_win.show();
	 }
	
	
	 
	function doOpertion(value, metaData, record, rowIndex, colIndex, store){
	         //var module = this;
	 	     var href0 = "<a style='font-size:12px' href=javascript:browserBuyItem"+"('"+record.data.docID+"')"+">查看</a>";
	         var href1 = "<a  style='font-size:12px' href=javascript:auditBuyItem"+"('"+record.data.docID+"')"+">审核</a>";	
	         var href;
	         if(record.data.state == 0){
	             href = href0+" | "+href1;
	         }else{
	             href = href0;
	         }
	         return href;
	 }
	
	
	 var cm=new Ext.grid.ColumnModel([new Ext.grid.RowNumberer(), 
	     {header : '操作',dataIndex:'docID',renderer:doOpertion},
		 {header : '入库单号',dataIndex: 'docID'},
		 {header : '购买日期',width : 120,dataIndex : 'buyDate',renderer:Ext.util.Format.dateRenderer('Y-m-d')},
		 {header : '供货单位',width:150,dataIndex:'partnerName'},		 
		 {header : '金额',width : 100,dataIndex : 'totalAmount'},
		 {header : '状态',width:90,dataIndex : 'stateName'},
		 {header : '经手人',width : 100,dataIndex : 'handler'},
		 {header : '入库人',width : 100,dataIndex : 'createMan'},
		 {header : '入库时间',width : 130,dataIndex : 'createTime',renderer:Ext.util.Format.dateRenderer('Y-m-d')},
		 {header : '审核人',width : 100,dataIndex : 'auditor'},
		 {header : '审核时间',width : 130,dataIndex : 'auditTime',renderer:Ext.util.Format.dateRenderer('Y-m-d')},
		 {header : '备注',width : 190,dataIndex : 'remarks'}
	 ]);
		
	
	 
	   var grid_debit = new Ext.grid.GridPanel({
        	title : '入库数据',
        	iconCls : 'icon-grid',
			region: 'center',
        	collapsible: false,
			border:false,
            margins: '5 0 0 0',
			columnLines :true,
			autoScroll : true,
			width : 600,
			enableHdMenu : false,
        	viewConfig:
        	{
        	 forceFit:false,
        	 scrollOffset:15
        	 },	   	   
        	autoWidth : true,
        	cm : cm,
        	ds : store,
        	sm : new Ext.grid.CheckboxSelectionModel({singleSelect : false}),
        	enableColumnMove : false,
        	trackMouseOver : false,
        	frame : true,
			bbar : new Ext.PagingToolbar({
        		pageSize: 20,
                store: store,
                displayInfo: true,
                 plugins: new Ext.ux.ProgressBarPager(),
        		items:[{   
                        text: '导出到Excel',   
                        tooltip: 'Excel'
                      }]
        	})
        	
        });	
		
	var p_debit = {
            layout: 'border',
            bodyBorder: false,
            defaults: {
                split: true,
                animFloat: false,
                autoHide: false,
                useSplitTips: true,
        		margins: '5 0 0 0',
                cmargins: '5 5 0 0'
            },
            items: [find_form,grid_debit]
        };	
		
	var vp = new Ext.Panel({
				region: 'center',
                deferredRender: false,
				layout : 'card',
				border : false,
                activeItem : 0,
				items : [p_debit]
			
        });
		
            win = desktop.createWindow({
                id: 'inRecord-win',
                title:'入库记录',
                width:app.maxWidth,
                height:app.maxHeight,
                iconCls: 'icon-grid',
                shim:false,
                animCollapse:false,
                constrainHeader:true,
                layout: 'border',
                items:[tb,vp]
            });
        }
        win.show();
    }
});
